<?php

namespace app\admin\service\yun;

use app\admin\model\yun\YunPhoneCdkBatch;
use app\admin\model\yun\YunPhoneCdkCode;
use app\admin\service\BaseService;
use think\Db;
use think\Exception;


/**
 * 云挂机服务类
 */
class BoxYunCdkCodeService extends BaseService
{

    /**
     * @var YunPhoneCdkBatch
     */
    protected $model;
    private $userId;

    public function __construct()
    {
        $this->model  = new YunPhoneCdkCode();
        $this->userId = request()->getUserId() ?? 0;
    }

    public function getList(): array
    {
        $params = request()->param();
        // $page      = request()->param('page', 1);
        $limit     = request()->param('limit', 10);
        $batch_id  = $params['batch_id'] ?? '';
        $status    = $params['status'] ?? '';
        $is_active = $params['is_active'] ?? '';
        $cdk       = $params['cdk'] ?? '';
        $time      = $params['time_range'] ?? [];
        if (!empty($time)) {
            $start_time = strtotime($time[0]);
            $end_time   = strtotime($time[1]);
            $where[]    = ['a.start_time', '>=', date('Y-m-d H:i:s', $start_time)];
            $where[]    = ['a.end_time', '<=', date('Y-m-d H:i:s', $end_time)];
        }

        if (!empty($batch_id)) $where[] = ['b.id', '=', $batch_id];
        if (!empty($status)) $where[] = ['a.status', '=', $status];
        if (!empty($is_active) || $is_active === '0') $where[] = ['a.is_active', '=', $is_active];
        if (!empty($cdk)) $where[] = ['a.cdk', '=', $cdk];

        $where[] = ['a.mark', '=', 1];
        $list    = $this->model->alias('a')
            ->leftJoin('yun_phone_cdk_batch b', 'a.batch_id = b.id')
            ->field('a.*,b.name as batch_name,b.duration')
            ->where($where)
            ->order('a.id', 'desc')
            ->paginate($limit)->toArray();
        //返回结果
        return array (
            "msg"   => '操作成功',
            "code"  => 0,
            "data"  => $list['data'],
            "count" => $list['total'],
        );
    }

    /**
     * Desc : edit
     * User : Steven
     * Date : 2024-05-22 13:11
     */
    public function edit()
    {
        // 参数
        $data       = request()->param();
        $batch_id   = $data['batch_id'] ?? 0;
        $prefix     = $data['prefix'] ?? '';
        $duration   = $data['duration'] ?? 0;
        $use_limit  = $data['use_limit'] ?? 0;
        $use_type   = $data['use_type'] ?? 0;
        $cdk_num    = $data['cdk_num'] ?? 0;
        $start_time = $data['time_range'][0] ?? '';
        $end_time   = $data['time_range'][1] ?? '';
        Db::startTrans();
        try {
            if (empty($batch_id)) throw new Exception('请选择批次');
            if ($batch_id == '9999999') {
                //快速创建
                $batch_id = (new YunPhoneCdkBatch())->insertGetId([
                    'user_id'   => $this->userId ?? 0,
                    'name'      => '快速创建_' . $prefix,
                    'prefix'    => $prefix,
                    'duration'  => $duration,
                    'use_limit' => $use_limit,
                    'use_type'  => $use_type,
                    'is_fast'   => 1
                ]);
                if ($cdk_num <= 0) throw new Exception('请输入生成数量');
                if (!$batch_id) throw new Exception('创建失败');

            }else{
                $batch_info = (new YunPhoneCdkBatch())->where('id', $batch_id)->find();
                if(empty($batch_info) || $batch_info['status'] == 2 || $batch_info['mark'] == 0) throw new Exception('批次不存在或已失效');
            }
            $insert          = [];
            for ($i = 0; $i < $cdk_num; $i++) {
                $insert[$i]['user_id']    = $this->userId ?? 0;
                $insert[$i]['batch_id']   = $batch_id;
                $insert[$i]['cdk']        = strtoupper($prefix.generateCode(6));
                $insert[$i]['start_time'] = date('Y-m-d H:i:s', strtotime($start_time));
                $insert[$i]['end_time']   = date('Y-m-d H:i:s', strtotime($end_time));
            }
            $result = $this->model->insertAll($insert);
            if (!$result) throw new Exception('生成失败');
            Db::commit();
            return message('操作成功', true);
        }catch (Exception $e){
            Db::rollback();
            return message($e->getMessage(), false);
        }
    }


    public function delete()
    {
        return parent::delete(); // TODO: Change the autogenerated stub
    }

    /**
     * Desc : startBatch
     * User : Steven
     * Date : 2024-05-21 20:05
     */
    public function startBatch(): array
    {
        $params = request()->param();
        $ids    = $params['id'] ?? '';
        $type   = $params['type'] ?? '';
        if (empty($ids) || empty($type)) {
            return message('参数错误', false);
        }
        Db::startTrans();
        try {
            if ($type == 1) {
                //批量开启
                $result = $this->model->where('id', 'in', $ids)->update(['status' => 1]);
                if (!$result) {
                    throw new Exception('操作失败');
                }
            } elseif ($type == 2) {
                //批量关闭
                $result = $this->model->where('id', 'in', $ids)->update(['status' => 2]);
                if (!$result) {
                    throw new Exception('操作失败');
                }
            }
            Db::commit();
            return message('操作成功', true);
        } catch (Exception $e) {
            Db::rollback();
            return message($e->getMessage(), false);
        }

    }
}